package org.example.threadpool;

import java.text.MessageFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class ThreadPoolApp {
    public static void main(String[] args) throws InterruptedException {
        start();

        ExecutorService pool = Executors.newFixedThreadPool(4);

//        ExecutorService pool = new ThreadPoolExecutor(
//                0, 4,
//                5L, TimeUnit.SECONDS,
//                new LinkedBlockingQueue<>());

        for (int i = 0; i < 10; i++) {
            Future<?> task = pool.submit(new MyRunnable());
        }

        pool.shutdown();

//        pool.submit(new MyRunnable()); // rejected

        // wait terminated
        pool.awaitTermination(1L, TimeUnit.SECONDS);

        log();
    }


    private static long startTime;

    private static void start() {
        startTime = System.currentTimeMillis();
    }

    private static long now() {
        return System.currentTimeMillis() - startTime;
    }

    private static void log() {
        System.out.println(MessageFormat.format("{0} {1} {2}",
                now(),
                Thread.currentThread().getId(),
                Thread.currentThread().getName()
        ));
    }

    private static class MyRunnable implements Runnable {
        @Override
        public void run() {
            log();
            sleep();
        }

        private void sleep() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                //
            }
        }
    }
}